package com.alks.function.service.serviceImpl.finance.fincons;


import com.alibaba.excel.EasyExcel;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.excelUtils.nestExcel.convert.DateConvert;
import com.alks.common.utils.excelUtils.nestExcel.entity.ExportEntity;
import com.alks.common.utils.excelUtils.nestExcel.handler.AutoWidthCellWriteHandler;
import com.alks.common.utils.excelUtils.nestExcel.handler.CellHandler;
import com.alks.common.utils.excelUtils.nestExcel.handler.HeadHandler;
import com.alks.common.utils.excelUtils.nestExcel.handler.MergeStrategy;
import com.alks.entity.data.entity.PcLotHead;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.chengKong.cost.pcStitchProdDetailDto;
import com.alks.function.data.dto.chengKong.cost.PcStitchProdDetailDto2;
import com.alks.function.data.dto.finance.fincons.InventoryPaymentDetailsDto;
import com.alks.function.data.request.chengKong.PcStitchProdDetailRequest;
import com.alks.function.data.request.finance.fincons.PcStitchDetailAttachRequest;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.chengKong.PcStitchProdDetailMapper;
import com.alks.function.mapper.finance.fincons.SewingProductionDataMapper;
import com.alks.function.service.finance.fincons.SewingProductionDataService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SewingProductionDataServiceImpl implements SewingProductionDataService {

    @Autowired
    private SewingProductionDataMapper sewingProductionDataMapper;

    @Autowired
    private PcStitchProdDetailMapper pcStitchProdDetailMapper;

    @Resource
    private PcLotHeadMapper pcLotHeadMapper;

    /**
     * 查询产量明细
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getYieldDetails(PcStitchProdDetailRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        //查询页面上的统计数量
        List<PcStitchProdDetailDto2> list = pcStitchProdDetailMapper.getPcStitchProdDetailList(request);

        //查询页面上的的统计数量
        //Integer countSum = pcStitchProdDetailMapper.getPcStitchProdDetailOfQtyCount(request);

        Map map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        //map.put("qytCount",countSum);
        return  ResponseInfo.ok(map);
    }

    /**
     * 查询产量明细的数量
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getYieldDetailsCount(PcStitchProdDetailRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);

        //查询页面上的的统计数量
        Integer countSum = pcStitchProdDetailMapper.getPcStitchProdDetailOfQtyCount(request);

        Map map = new HashMap<>();
        map.put("qytCount",countSum);
        return  ResponseInfo.ok(map);
    }

    /**
     * 缴库明细查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getInventoryPaymentDetails(PcStitchDetailAttachRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        //缴库明细查询
        List<InventoryPaymentDetailsDto> list = sewingProductionDataMapper.getCostDetailsList(companyId,request);

        //查询缴库明细的统计数量
        //Integer countSum = sewingProductionDataMapper.getCostDetailsOfQtyCount(companyId,request);

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        //map.put("count3",countSum);
        return ResponseInfo.ok(map);
    }

    /**
     * 查询缴库明细的已报产量
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getInventoryPaymentCount(PcStitchDetailAttachRequest request) {
        String companyId = UserIdThread.get().getCompanyId();

        //查询缴库明细的统计数量
        Integer countSum = sewingProductionDataMapper.getCostDetailsOfQtyCount(companyId,request);

        HashMap map = new HashMap<>();
        map.put("countSum",countSum);
        return ResponseInfo.ok(map);
    }

    /**
     * 导出产量明细
     * @param request
     * @param response
     */
    @Override
    public void exportYieldDetails(PcStitchProdDetailRequest request, HttpServletResponse response) throws IOException  {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        //查询页面上的统计数量
        List<PcStitchProdDetailDto2> list = pcStitchProdDetailMapper.getPcStitchProdDetailList(request);

        BigDecimal countAmt = BigDecimal.ZERO;
        if(ObjectUtils.isNotEmpty(list)){
            for (PcStitchProdDetailDto2 dto : list) {
                if (dto != null && dto.getAmt() != null) {
                    countAmt = countAmt.add(dto.getAmt());
                }
            }
        }


        Map<String, Object> map = new HashMap<>();
        map.put("countAmt",countAmt);
        ExcelUtils.creatByTemplate(response,"针车员工产量明细表模板.xls","针车员工产量明细表_"+DateUtils.dateTimeNow(),list,map);
    }


    /**
     * 导出指令产量明细
     * @param request
     * @param response
     */
    @Override
    public void exportLotNoYield(PcStitchProdDetailRequest request, HttpServletResponse response) {
        //1.先查出所有的数据
        String companyId = UserIdThread.get().getCompanyId();

        PcLotHead pcLotHead = pcLotHeadMapper.selectOne(
                new LambdaQueryWrapper<PcLotHead>().eq(PcLotHead::getLotNo, request.getLotNo())
                        .eq(PcLotHead::getCompanyId, companyId));

        request.setCompanyId(companyId);
        request.setPageNum(1);
        request.setPageSize(Integer.MAX_VALUE);
        List<PcStitchProdDetailDto2> list = pcStitchProdDetailMapper.getPcStitchProdDetailList2(request);
        if(ObjectUtils.isEmpty(list)){
            throw new ServiceErrorException("未查询到数据");
        }
        // 工序分组
        Map<String, List<PcStitchProdDetailDto2>> processMap = list.stream()
                .collect(Collectors.groupingBy(PcStitchProdDetailDto2::getProcessName));

        // 单位分组
        Map<String, List<PcStitchProdDetailDto2>> deptMap = list.stream()
                .collect(Collectors.groupingBy(PcStitchProdDetailDto2::getDeptName));

        List<List<String>> headers = new ArrayList<>();
        String line1 = String.format("%s产量明细", request.getLotNo());
        if (pcLotHead != null) {
            line1 += String.format("（冲刀号：%s 型体：%s 订单量：%s）", pcLotHead.getCutNo(), pcLotHead.getStyle(), pcLotHead.getTotalQty());
        }
        List<String> c1 = new ArrayList<>();
        c1.add(line1);
        c1.add("序号");
        c1.add("序号");
        headers.add(c1);
        List<String> c2 = new ArrayList<>();
        c2.add(line1);
        c2.add("工序名称");
        c2.add("工序名称");
        headers.add(c2);

        List<String> headCol = new ArrayList<>();// 表头字段
        for (Map.Entry<String, List<PcStitchProdDetailDto2>> entry : deptMap.entrySet()) {
            Set<String> workList = new HashSet<>();
            Map<String, String> id2WorkNameMap = new HashMap<>();
            for (PcStitchProdDetailDto2 temDto : entry.getValue()) {
                workList.add(temDto.getWorkId());
                if (!id2WorkNameMap.containsKey(temDto.getWorkId())) {
                    id2WorkNameMap.put(temDto.getWorkId(), temDto.getWorkName());
                }
            }
            for (String worker : workList) {
                headCol.add(worker);
                List<String> c = new ArrayList<>();
                c.add(line1);
                c.add(entry.getKey());
                c.add(id2WorkNameMap.get(worker));
                headers.add(c);
            }
            List<String> c = new ArrayList<>();
            c.add(line1);
            c.add(entry.getKey());
            c.add("合计");
            headers.add(c);
            headCol.add("total");
        }

        // 拼接数据
        List<List<String>> dataList = new ArrayList<>();
        int tag = 1;
        for (Map.Entry<String, List<PcStitchProdDetailDto2>> entry : processMap.entrySet()) {
            List<String> line = new ArrayList<>();
            line.add(String.valueOf(tag++));
            line.add(entry.getKey());
            // 根据工号分组  同一个工序一个人可能有多条记录
            Map<String, List<PcStitchProdDetailDto2>> dataMap = entry.getValue().stream()
                    .collect(Collectors.groupingBy(PcStitchProdDetailDto2::getWorkId));
            long total = 0L;
            for (String s : headCol) {
                if (dataMap.containsKey(s)) {
                    // 累计个人某一工序的总和
                    long qty = dataMap.get(s).stream().mapToLong(e->e.getQty().longValue()).sum();
                    line.add(String.valueOf(qty));
                    total += qty;
                } else {
                    if ("total".equals(s)) {
                        line.add(String.valueOf(total));
                        total = 0L;
                    } else {
                        line.add(null);
                    }
                }
            }
            dataList.add(line);
        }

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + request.getLotNo() + "_" +System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream()).sheet("指令产量明细")
                    .head(headers)
                    .registerWriteHandler(new AutoWidthCellWriteHandler(2))
                    .registerWriteHandler(new CellHandler(dataList))
                    .doWrite(dataList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 导出缴库明细
     * @param request
     * @param response
     */
    @Override
    public void exportInventoryPaymentDetails(PcStitchDetailAttachRequest request, HttpServletResponse response)  throws IOException {
        String companyId = UserIdThread.get().getCompanyId();
        //缴库明细查询
        List<InventoryPaymentDetailsDto> list = sewingProductionDataMapper.getCostDetailsList(companyId,request);

        BigDecimal seqCount = BigDecimal.ZERO;
        BigDecimal minQtyCount = BigDecimal.ZERO;
        if(ObjectUtils.isNotEmpty(list)){
            for (InventoryPaymentDetailsDto dto : list) {
                if (dto != null ) {
                    if( dto.getSeqDidCount() != null){
                        seqCount = seqCount.add(dto.getSeqDidCount());
                    }
                    if(dto.getMinQty() != null){
                        minQtyCount = minQtyCount.add(dto.getMinQty());
                    }
                }
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("seqCount",seqCount); //已报道序
        map.put("minQtyCount",minQtyCount); //已报产量
        ExcelUtils.creatByTemplate(response,"缴库明细模板.xls","缴库明细_"+DateUtils.dateTimeNow(),list,map);
    }

}
